﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer.Manager;
using Objects;
using AutoFix.Base;
using AutoFix.controls;
using AutoFix.ClientComponents;
using System.Web.Services;
using System.Web.Script.Serialization;
using Common;
using System.IO;
namespace AutoFix
{
    public partial class add_model : BasePage
    {
        #region [Private Members]
        /// <summary>
        /// stores the logged in user
        /// </summary>
        private User applicationUser = null;

        #endregion

        #region [Public Properties]
        /// <summary>
        /// Get/Set Vehicle model type name
        /// </summary>
        public string VehicleModelTypeName { get; set; }
        /// <summary>
        /// Get/Set Vehicle model type year name
        /// </summary>
        public string VehicleModelYearName { get; set; }
        #endregion

        #region [Private Properties]
        /// <summary>
        /// Stores the vehicle model id
        /// </summary>
        private int VehicleModelID { get; set; }
        /// <summary>
        /// Stores the vehicle model type id
        /// </summary>
        private int VehicleModelTypeID { get; set; } 
        #endregion

        #region [BasePage Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage { get { return false; } }

        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage { get { return false; } }
        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Add Model"; }
        }
        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin }); }
        }
      
        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            applicationUser = this.PageSession.ApplicationUser;
        }
        /// <summary>
        /// Handles the click event of the add model button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnAddModel_Click(object sender, EventArgs e)
        {

            string vehicleModelName = ToTitleCase(this.txtVehicleModel.Text.Trim());
            VehicleModelTypeName = ToTitleCase(this.txtVehicleModelType.Text.Trim());
            VehicleModelYearName = this.txtVehicleModelTypeYear.Text.Trim();
            VehicleModelManager vehicleModelManager = new VehicleModelManager();
            VehicleModel vehicleModel = new VehicleModel();
            List<VehicleModel> vehicleModels = null;

            try
            {
                if ((vehicleModelName != string.Empty || this.hdnModelSelectedValue.Value != string.Empty)
                    && (VehicleModelTypeName != string.Empty || this.hdnModelTypeSelectedValue.Value != string.Empty)
                    && (VehicleModelYearName != string.Empty || this.hdnModelTypeYearSelectedValue.Value != string.Empty))
                {
                    if (this.txtVehicleModel.Text != "")
                    {
                        vehicleModel.VehicleModelName = this.txtVehicleModel.Text;
                    }
                    else
                    {
                        vehicleModel.VehicleModelName = vehicleModelName;
                    }
                    vehicleModel.IsActive = true;
                    vehicleModels = vehicleModelManager.GetVehicleModels();
                    if (vehicleModels.Count == 0)
                    {
                        vehicleModels = vehicleModelManager.UpdateVehicleModelScalar(vehicleModel);
                        if (vehicleModels != null && vehicleModels[0].VehicleModelID > 0)
                        {
                            this.VehicleModelID = vehicleModels[0].VehicleModelID;
                            AddVehicleModelType();
                        }
                        else
                        {
                            this.pageActionMessage.InnerText = "vehicle model wasn't added to the system";
                            this.pageActionMessage.Attributes.Add("class", "error-msg");
                        }


                    }
                    else
                    {

                        if (!(this.txtVehicleModel.Text == string.Empty))
                        {
                            vehicleModels = vehicleModelManager.UpdateVehicleModelScalar(vehicleModel);
                            if (vehicleModels == null)
                            {
                                this.pageActionMessage.InnerText = "Failed to retrieve vehicle model from the system";
                                this.pageActionMessage.Attributes.Add("class", "error-msg");
                                return;
                            }
                            if (vehicleModels != null && vehicleModels[0].VehicleModelID > 0)
                            {
                                this.VehicleModelID = vehicleModels[0].VehicleModelID;
                                AddVehicleModelType();
                            }
                            else
                            {
                                vehicleModels = vehicleModelManager.UpdateVehicleModelScalar(vehicleModel);

                                if (vehicleModels != null && vehicleModels[0].VehicleModelID > 0)
                                {
                                    this.VehicleModelID = vehicleModels[0].VehicleModelID;
                                    AddVehicleModelType();

                                }
                                else
                                {
                                    this.pageActionMessage.InnerText = "Failed to add vehicle model to the system";
                                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                                    return;
                                }
                            }

                        }
                        else
                        {
                            vehicleModels = vehicleModelManager.GetVehicleModelsByID(Convert.ToInt32(hdnModelInfo.Value));
                            if (vehicleModels == null)
                            {
                                this.pageActionMessage.InnerText = "Failed to retrieve vehicle model from the system";
                                this.pageActionMessage.Attributes.Add("class", "error-msg");
                                return;
                            }
                            if (vehicleModels != null && vehicleModels[0].VehicleModelID > 0)
                            {
                                this.VehicleModelID = vehicleModels[0].VehicleModelID;
                                AddVehicleModelType();
                            }
                            else
                            {
                                vehicleModels = vehicleModelManager.UpdateVehicleModelScalar(vehicleModel);

                                if (vehicleModels != null && vehicleModels[0].VehicleModelID > 0)
                                {
                                    this.VehicleModelID = vehicleModels[0].VehicleModelID;
                                    AddVehicleModelType();

                                }
                                else
                                {
                                    this.pageActionMessage.InnerText = "Failed to add vehicle model to the system";
                                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                                    return;
                                }
                            }
                        }


                    }


                }
            }
            catch (Exception)
            {

                this.pageActionMessage.InnerText = "Failed to add vehicle model to the system";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                vehicleModelManager = null;
                vehicleModel = null;
                vehicleModels = null;
            }
        }
        #endregion   
  
        #region [Web Methods]
        /// <summary>
        /// Gets the model type years
        /// </summary>
        /// <param name="vehicleModelTypeID">vehicleModelTypeID</param>
        /// <returns>serialized model years</returns>
        [WebMethod]
        public static string GetModelTypeYears(string vehicleModelTypeID)
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelTypeYearManager vehicleModelTypeYearManager = new VehicleModelTypeYearManager();
            List<VehicleModelTypeYear> vehicleModelTypeYears = null;
            string returnedString = string.Empty;

            try
            {
                vehicleModelTypeYears = vehicleModelTypeYearManager.GetVehicleModelTypeYears();
                foreach (VehicleModelTypeYear vehicleModelTypeYear in vehicleModelTypeYears)
                {
                    if (Convert.ToInt16(vehicleModelTypeID) == vehicleModelTypeYear.VehicleModelTypeYearID)
                    {
                        if (vehicleModelTypeYear.IsActive != false)
                        {
                            resultList.Add(new KeyValuePair<string, string>(vehicleModelTypeYear.VehicleModelTypeYearID.ToString(), vehicleModelTypeYear.VehicleYear.ToString()));
                        }

                    }

                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeYearManager = null;
                vehicleModelTypeYears = null;
            }
            return returnedString;
        }

        /// <summary>
        /// Gets the model types
        /// </summary>
        /// <param name="vehicleModelID">vehicleModelID</param>
        /// <returns>serialized model types</returns>
        [WebMethod]
        public static string GetModelTypes(string vehicleModelID)
        {

            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelTypeManager vehicleModelTypeManager = new VehicleModelTypeManager();
            List<VehicleModelType> vehicleModelTypes = null;
            string returnedString = string.Empty;
            try
            {
                vehicleModelTypes = vehicleModelTypeManager.GetVehicleModelTypes();
                foreach (VehicleModelType vehicleModelType in vehicleModelTypes)
                {
                    if (Convert.ToInt32(vehicleModelID) == vehicleModelType.VehicleModelID)
                    {
                        if (vehicleModelType.IsActive != false)
                        {
                            resultList.Add(new KeyValuePair<string, string>(vehicleModelType.VehicleModelTypeID.ToString(), vehicleModelType.VehicleModelTypeName));
                        }

                    }

                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeManager = null;
                vehicleModelTypes = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the vehicle models
        /// </summary>
        /// <returns>serialized models</returns>
        [WebMethod]
        public static string GetAllModels()
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<string, string>> resultList = new List<KeyValuePair<string, string>>();
            VehicleModelManager vehicleModelManager = new VehicleModelManager();
            List<VehicleModel> vehicleModels = null;
            string returnedString = string.Empty;

            try
            {
                vehicleModels = vehicleModelManager.GetVehicleModels();
                foreach (VehicleModel vehicleModel in vehicleModels)
                {
                    if (vehicleModel.IsActive != false)
                    {
                        resultList.Add(new KeyValuePair<string, string>(vehicleModel.VehicleModelID.ToString(), vehicleModel.VehicleModelName));
                    }
                }

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelManager = null;
                vehicleModels = null;
            }
            return returnedString;
        }
        /// <summary>
        /// Gets the vehicle model image
        /// </summary>
        /// <returns>serialized model image</returns>
        [WebMethod]
        public static string GetModelImage(string vehicleModelTypeID)
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            List<KeyValuePair<int, string>> resultList = new List<KeyValuePair<int, string>>();
            VehicleModelTypeYearManager vehicleModelTypeYearManager = new VehicleModelTypeYearManager();
            List<ModelTypeImage> modelTypeImages = null;
            string returnedString = string.Empty;

            try
            {
                modelTypeImages = vehicleModelTypeYearManager.GetVehicleModelTypeImage(Convert.ToInt32(vehicleModelTypeID));
                if (modelTypeImages[0].VehicleModelTypeImageURL != string.Empty)
                {

                    string folderName = "/" + modelTypeImages[0].VehicleModelTypeImageURL.Substring(0, modelTypeImages[0].VehicleModelTypeImageURL.IndexOf(".jpg")) + "/";
                    resultList.Add(new KeyValuePair<int, string>(0, AppConfiguration.VehicleImagePath + folderName + modelTypeImages[0].VehicleModelTypeImageURL));
                    
                }
                else
                {
                    resultList.Add(new KeyValuePair<int, string>(0, "images/imgNoModelImage.png"));
                }

                

                returnedString = jsonSerialize.Serialize(resultList);

            }
            catch
            {

            }
            finally
            {
                jsonSerialize = null;
                resultList = null;
                vehicleModelTypeYearManager = null;
                modelTypeImages = null;
            }
            return returnedString;
        } 
        #endregion

        #region [Private Methods]
        /// <summary>
        /// Method that converts string to title case
        /// </summary>
        /// <param name="textBox">the textbox value</param>
        /// <returns>the titled case value</returns>
        private string ToTitleCase(string textBox)
        {
            string titleCase = string.Empty;
            if (!(string.IsNullOrEmpty(textBox)))
            {
                titleCase = textBox.ToString().ToUpper().First() + String.Join("", textBox.Skip(1)).ToLower();
            }
            return titleCase;
        }
        /// <summary>
        /// Method that adds the vehicle model type in table
        /// </summary>
        private void AddVehicleModelType()
        {
            VehicleModelTypeManager vehicleModelTypeManager = new VehicleModelTypeManager();
            VehicleModelType vehicleModelType = new VehicleModelType();
            List<VehicleModelType> vehicleModelTypes = null;
            try
            {
                if (this.txtVehicleModelType.Text != "")
                {
                    vehicleModelType.VehicleModelTypeName = this.txtVehicleModelType.Text;
                }
                else
                {
                    vehicleModelType.VehicleModelTypeName = VehicleModelTypeName;
                }
                vehicleModelType.VehicleModelID = this.VehicleModelID;
                vehicleModelType.IsActive = true;
                vehicleModelTypes = vehicleModelTypeManager.GetVehicleModelTypes();
                if (vehicleModelTypes.Count == 0)
                {
                    vehicleModelTypes = vehicleModelTypeManager.UpdateVehicleModelTypeScalar(vehicleModelType);
                    if (vehicleModelTypes != null && vehicleModelTypes[0].VehicleModelTypeID > 0)
                    {
                        this.VehicleModelTypeID = vehicleModelTypes[0].VehicleModelTypeID;
                        AddModelYear();
                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "Failed to add model type to the system";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                }
                else
                {
                    if (hdnIsModelTypeExists.Value == string.Empty)
                    {
                        vehicleModelTypes = vehicleModelTypeManager.UpdateVehicleModelTypeScalar(vehicleModelType);
                        if (vehicleModelTypes != null && vehicleModelTypes[0].VehicleModelTypeID > 0)
                        {
                            this.VehicleModelTypeID = vehicleModelTypes[0].VehicleModelTypeID;
                            AddModelYear();
                        }
                        else
                        {
                            this.pageActionMessage.InnerText = "Failed to add model type to the system";
                            this.pageActionMessage.Attributes.Add("class", "error-msg");
                        }
                    }
                    else
                    {
                        vehicleModelTypes = vehicleModelTypeManager.GetVehicleModelTypeByID(Convert.ToInt32(hdnModelTypeInfo.Value));
                        if (vehicleModelTypes == null)
                        {
                            this.pageActionMessage.InnerText = "Failed to retrieve vehicle model type from the system";
                            this.pageActionMessage.Attributes.Add("class", "error-msg");
                            return;
                        }
                        if (vehicleModelTypes != null && vehicleModelTypes[0].VehicleModelID > 0)
                        {
                            this.VehicleModelTypeID = vehicleModelTypes[0].VehicleModelTypeID;
                            AddModelYear();
                        }
                        else
                        {
                            vehicleModelTypes = vehicleModelTypeManager.UpdateVehicleModelTypeScalar(vehicleModelType);
                            if (vehicleModelTypes != null && vehicleModelTypes[0].VehicleModelTypeID > 0)
                            {
                                this.VehicleModelTypeID = vehicleModelTypes[0].VehicleModelTypeID;
                                AddModelYear();
                            }
                            else
                            {
                                this.pageActionMessage.InnerText = "Failed to add model type to the system";
                                this.pageActionMessage.Attributes.Add("class", "error-msg");
                            }
                        }
                    }

                }
            }
            catch (Exception)
            {

                this.pageActionMessage.InnerText = "Failed to add model type to the system";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                vehicleModelTypeManager = null;
                vehicleModelType = null;
                vehicleModelTypes = null;
            }
        }
        /// <summary>
        /// Method that adds the model year in table
        /// </summary>
        private void AddModelYear()
        {
            VehicleModelTypeYearManager vehicleModelTypeYearManager = new VehicleModelTypeYearManager();
            VehicleModelTypeYear vehicleModelTypeYear = new VehicleModelTypeYear();
            bool IsModelTypeYearSuccess = false;
            string file = string.Empty;
            try
            {

                vehicleModelTypeYear.VehicleModelTypeID = this.VehicleModelTypeID;
                vehicleModelTypeYear.IsActive = true;
                vehicleModelTypeYear.VehicleYear = Convert.ToInt32((VehicleModelYearName != string.Empty) ? Convert.ToInt32(VehicleModelYearName) : Convert.ToInt32(this.hdnModelTypeYearSelectedValue.Value));
                
                if (this.fleVehicleImage.HasFile)
                {
                    if (this.fleVehicleImage.PostedFile.ContentType == "image/jpeg")
                    {
                        Guid guid = Guid.NewGuid();

                        string pathToFile = AppConfiguration.VehicleImagePath + guid + "/";
                        string fileToStore = guid + ".jpg";

                        string completeDirectoryPath = Server.MapPath(pathToFile);
                        if (!Directory.Exists(pathToFile))
                        {
                            Directory.CreateDirectory(completeDirectoryPath);
                            completeDirectoryPath = Path.Combine(completeDirectoryPath, fileToStore);
                            if (!File.Exists(completeDirectoryPath))
                            {
                                file = completeDirectoryPath;
                                vehicleModelTypeYear.VehicleModelTypeImageURL = fileToStore;
                                this.fleVehicleImage.SaveAs(file);
                            }
                        }

                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "Invalid image file. Only jpg format is allowed";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                        return;
                    }
                }
                else
                {
                    vehicleModelTypeYear.VehicleModelTypeImageURL = "";
                }
                IsModelTypeYearSuccess = vehicleModelTypeYearManager.UpdateVehicleModelTypeYear(vehicleModelTypeYear);
                if (IsModelTypeYearSuccess)
                {

                    this.pageActionMessage.InnerText = "vehicle model information was successfully added to the system";
                    this.pageActionMessage.Attributes.Add("class", "success-msg");
                }
                else
                {
                    this.pageActionMessage.InnerText = "vehicle model year wasn't added to the system";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception)
            {

                this.pageActionMessage.InnerText = "Failed to add model type to the system";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                vehicleModelTypeYearManager = null;
                vehicleModelTypeYear = null;
            }
        } 
        #endregion

    }
}